module("luci.controller.admin.nwt",package.seeall)

function index()
	entry({"admin","nwt"},alias("admin","nwt","serial"),"控制器",50).index=true
	entry({"admin","nwt","serial"},cbi("admin_nwt/serial",{hidesavebtn=true, hideresetbtn=true}),"串口",1)
	e=entry({"admin","nwt","device"},arcombine(cbi("admin_nwt/devices"),cbi("admin_nwt/device")),"设备",2)
	e.leaf=true
	e.subindex=true
	if e.inreq then
		local ctrl = require "luci.tools.nwt"
		local devicelist = ctrl.get_devicelist()
		if type(devicelist) == "table" then
			for _,device in pairs(devicelist) do
				entry({"admin","nwt","device",device.address},true)
			end
		end
	end

	entry({"admin","nwt","device_add"},cbi("admin_nwt/device_add"),nil).leaf=true
	entry({"admin","nwt","device_delete"},post("device_delete"),nil).leaf=true
end

function device_delete(addr)
	local nfs   = require "nixio.fs"
	local json = require "luci.jsonc"
	if addr and#addr>0 then
		local nwtconf = json.parse(nfs.readfile("/etc/nwt.json") or "")
		if type(nwtconf) == "table" then
			for i,value in pairs(nwtconf.devices) do
				if addr == value.address then
					--remove
					table.remove(nwtconf.devices,i) 
				end
			end
			--save
			local js = json.stringify(nwtconf)
			nfs.writefile("/etc/nwt.json",js)
			--TODO restart serial client
			luci.sys.call("/etc/init.d/nwt restart")
		end
	end
	return
end